﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

public class CharViewerPawn : MonoBehaviour {

	Dictionary<CharacterViewer.EViewerTake ,TakeInfo> takeDic = new Dictionary<CharacterViewer.EViewerTake, TakeInfo>();
	UnityEngine.Object[] actorMe;
	ECharModel charModel;
	string charModelStr;
	bool isPlayer;
	IEventlinePlayer takePlayer;
	public string curTakeName;
	public CharacterViewer.EViewerTake eCurTake;
	public EventlineTake curTake;
	bool isHealer;
	CharViewerPawn enemy;
	GameObject enemyGo;
	public BattleCharInfo charInfo;
	Vector3 originalPos;
	public Transform damagePointTrans;
	public Transform castPointTrans;
	public CharViewerProjectile projectile;
	public bool isSupportAtkMove;
	public bool isSupportDef;
	GameObject [] dummygo;
	bool isMassBattleTake;

	public void Init(bool _isPlayer)
	{
		charInfo = GetComponent<BattleCharInfo>();
		charInfo.ShowShadow();
		originalPos = transform.position;

		if(damagePointTrans==null)
			damagePointTrans = BattleUtil.SearchHierarchyForBone(transform, "Damage_point");
		


		BattleResManager.AttachWeapon( gameObject, charInfo, null, true);	

		isPlayer = _isPlayer;
		if(actorMe==null) {
			actorMe = new UnityEngine.Object[1];
			actorMe[0] = this.gameObject;
		}

		charModel = BattleResManager.FindCharModel(gameObject.name);
		charModelStr = charModel.ToString();

		isHealer = BattleResManager.IsHealerModel(charModel);
		if(isHealer) {
			dummygo = new GameObject[3];
			for(int i=0; i<3; i++) {
				dummygo[i] = new GameObject();
				dummygo[i].transform.position = new Vector3(100,100,0);
			}
		}

		if(_isPlayer && charInfo.isCaster) {
			if(castPointTrans==null)
				castPointTrans = BattleUtil.SearchHierarchyForBone(transform, "CastPoint");
			BattleResManager.Instance.LoadProjectile(charModel.ToString(), charInfo.projectileInfo);
		}

		string myModelStrTmp = charModelStr;
		if(charModel== ECharModel.Chanter)
			myModelStrTmp += "_M";
		else if(charModel== ECharModel.Cleric)
			myModelStrTmp += "_W";
		else if(charModel== ECharModel.Gladiator)
			myModelStrTmp += "_M";
		else if(charModel== ECharModel.LycanRanger)
			myModelStrTmp += "_M";
		else if(charModel== ECharModel.Ranger)
			myModelStrTmp += "_W";
		string takePath = "";
		if( gameObject.name.Contains("_Low") ) {
			isMassBattleTake=true;
			if(charModel== ECharModel.Assassin)
				myModelStrTmp += "_M";
			else if(charModel== ECharModel.Sorcerer)
				myModelStrTmp += "_W";
			else if(charModel== ECharModel.Spiritmaster)
				myModelStrTmp += "_W";
			takePath = "MassBattle/"+myModelStrTmp+"/";
		}
		else
			takePath = myModelStrTmp+"/";
		Debug.Log("takepath  ="+takePath);

		if(_isPlayer)
			TakePopupList.Instance.ClearList();

		foreach (CharacterViewer.EViewerTake etake in Enum.GetValues(typeof(CharacterViewer.EViewerTake)))
		{
			if(etake== CharacterViewer.EViewerTake.Max)
				continue;
			if( takeDic.ContainsKey( etake ) )
				continue;
			if(!isPlayer) {
				if(etake != CharacterViewer.EViewerTake.idle01 && etake != CharacterViewer.EViewerTake.damage01)
					continue;
			}
			string _takeName = etake.ToString();
			EventlineTake newTake = Eventline.LoadTake(takePath+_takeName);
			if( newTake == null )
				continue;
			//Debug.LogError("load take   "+takePath+etake.ToString());
			TakeInfo tinfo = new TakeInfo();
			tinfo.take = newTake;
			Debug.Log(charModel+ "   loadTake  "+_takeName);
			takeDic.Add(etake, tinfo);
			if(_isPlayer)
				TakePopupList.Instance.AddList(_takeName);
		}
		if(_isPlayer)
			TakePopupList.Instance.SetIdle();
		else
			PlayIdle();
	}

	public void PlayIdle()
	{
		PlayEventlineTake(CharacterViewer.EViewerTake.idle01,true);
	}

	public void PlayIdleDontStopCurTake()
	{
		PlayEventlineTake(CharacterViewer.EViewerTake.idle01, true, actorMe, false);
	}

	public float PlayEventlineTake(CharacterViewer.EViewerTake _takeEnum, bool isLoop)
	{
		return PlayEventlineTake(_takeEnum, isLoop, actorMe);
	}

	float PlayEventlineTake(CharacterViewer.EViewerTake _takeEnum, bool isLoop, UnityEngine.Object [] actors)
	{
		return PlayEventlineTake(_takeEnum, isLoop, actors, true);
	}

	float PlayEventlineTake(CharacterViewer.EViewerTake _takeEnum, bool isLoop, UnityEngine.Object [] actors, bool bStopCurTake)
	{
		if(!takeDic.ContainsKey(_takeEnum)) {
			Debug.LogError("take dic not contain key "+_takeEnum);
			return 0;
		}

		if(bStopCurTake)
			StopCurTake();
		curTakeName = _takeEnum.ToString();
		eCurTake = _takeEnum;
		curTake = takeDic[_takeEnum].take;
		Debug.Log(gameObject.name +"  PlayEventlineTake  "+curTakeName);
		//StartCoroutine(CoPlayTake(_takeEnum, isLoop, actors));
		takePlayer = Eventline.Play ( takeDic[_takeEnum].take, actors, this.gameObject, isLoop);
		return 0;
	}

//	IEnumerator CoPlayTake(ETake _takeEnum, bool isLoop, UnityEngine.Object [] actors)
//	{
//		yield return new WaitForSeconds(0.5f);
//		takePlayer = Eventline.Play ( takeDic[_takeEnum].take, actors, this.gameObject, isLoop);
//	}

	public void StopCurTake()
	{
		curTakeName = "";
		eCurTake = CharacterViewer.EViewerTake.Max;
		if(takePlayer!=null)
		{
			takePlayer.Stop();
			takePlayer = null;
		}
		curTake = null;
	}

	public void PlayTake(CharacterViewer.EViewerTake takeToPlay, GameObject _enemyGo, CharViewerPawn _enemy)
	{
		isSupportAtkMove=false;
		isSupportDef=false;
		//StopCurTake();
		enemy = _enemy;
		enemyGo = _enemyGo;
		if(takeToPlay== CharacterViewer.EViewerTake.idle01 || takeToPlay== CharacterViewer.EViewerTake.idle02 || takeToPlay== CharacterViewer.EViewerTake.downloop01) {
			transform.position = originalPos;
			PlayEventlineTake(takeToPlay, true);
		}
		else {
			if(takeToPlay== CharacterViewer.EViewerTake.attack01) {
				UnityEngine.Object[] actors = { actorMe[ 0 ], ( UnityEngine.Object )enemyGo };		
				PlayEventlineTake(takeToPlay,false, actors);
			}
			else if(takeToPlay== CharacterViewer.EViewerTake.support_attack01) {
				isSupportAtkMove=true;
				UnityEngine.Object[] actors = { actorMe[ 0 ], ( UnityEngine.Object )enemyGo, ( UnityEngine.Object )Camera.main.gameObject };		
				PlayEventlineTake(takeToPlay,false, actors);
			}
			else if(takeToPlay== CharacterViewer.EViewerTake.support_guard01) {
				isSupportDef=true;
				PlayEventlineTake(takeToPlay,false);
			}
			else if(takeToPlay== CharacterViewer.EViewerTake.skill01 || takeToPlay== CharacterViewer.EViewerTake.skill01_S) {
				if(!CharacterViewer.Instance.turnOffSkillCam) {
					CharacterViewer.Instance.touchCam.DeactivateFreeCam();
					CharacterViewer.Instance.BackToOriginalCamPos(1);
				}
				if(isHealer) {
					if(isMassBattleTake) {
						UnityEngine.Object[] actors = { actorMe[ 0 ], ( UnityEngine.Object )enemyGo , ( UnityEngine.Object )CharacterViewer.Instance.cameraRoot};
						PlayEventlineTake(takeToPlay,false,actors);
					}
					else {
						UnityEngine.Object[] actors = { actorMe[ 0 ], ( UnityEngine.Object )dummygo[0] ,( UnityEngine.Object )dummygo[1] ,( UnityEngine.Object )dummygo[2] , ( UnityEngine.Object )CharacterViewer.Instance.cameraRoot};
						PlayEventlineTake(takeToPlay,false,actors);
					}
				}
				else {
					UnityEngine.Object[] actors = { actorMe[ 0 ], ( UnityEngine.Object )enemyGo , ( UnityEngine.Object )CharacterViewer.Instance.cameraRoot};
					PlayEventlineTake(takeToPlay,false,actors);
				}
			}
			else if(takeToPlay== CharacterViewer.EViewerTake.damage01) {
				UnityEngine.Object[] actors = { actorMe[ 0 ], (UnityEngine.Object)CharacterViewer.Instance.middleCam };
				PlayEventlineTake(takeToPlay,false,actors);
			}
			else if(takeToPlay== CharacterViewer.EViewerTake.forward01) {
				UnityEngine.Object[] actors = { actorMe[ 0 ], ( UnityEngine.Object )enemyGo };		
				PlayEventlineTake(takeToPlay,false, actors);
			}
			else
				PlayEventlineTake(takeToPlay, false);
		}
	}

	public void OnDamage()
	{
		UnityEngine.Object[] actors = { actorMe[ 0 ], (UnityEngine.Object)CharacterViewer.Instance.middleCam };
		PlayEventlineTake(CharacterViewer.EViewerTake.damage01,false,actors);
	}

	/// 
	/// Event  	/// 
	/// 
	/// 

	public void EndOfPlay(IEventlinePlayer takePlayer)
	{
		if(takePlayer.IsLooping)
			return;
		GameObject mainActor = (GameObject)takePlayer.MainActor;
		//Debug.Log(" ################ EndOfPlay event   "+gameObject.name+"    "+takePlayer.Take.Name);
		
		if(takePlayer.Take == curTake)
		{
			if(CharacterViewer.Instance.repeatPlay && isPlayer)
				PlayTake(eCurTake, enemyGo, enemy);
			else {
				if(eCurTake== CharacterViewer.EViewerTake.attack01 || eCurTake== CharacterViewer.EViewerTake.support_attack01 || eCurTake== CharacterViewer.EViewerTake.support_guard01 || eCurTake== CharacterViewer.EViewerTake.skill01 || eCurTake== CharacterViewer.EViewerTake.damage01 || eCurTake== CharacterViewer.EViewerTake.enterstage01)
					PlayIdleDontStopCurTake();
			}
		}

	}

	public void hit(System.Object[] objs)
	{
		if(isHealer) {
			//foreach(BattlePawn pawn in manifest.healTargetList)
			//	pawn.OnHeal( manifest.healPercent);
		}
		else {
			enemy.OnDamage();
		}
	}

	//이동//
	public void move(System.Object[] objs)
	{   
		if (1 < objs.Length)
		{
			string dir = objs[0] as string;
			string dur = objs[1] as string;
			float fDuration = float.Parse(dur);
			Debug.Log(gameObject.name+"   "+dir+"  ********* Move   "+dur);
			if(dir=="f") {
				if( (isSupportAtkMove && charInfo.isCaster) || isSupportDef)
					LeanTween.move(gameObject, BattleUtil.GetPosToTarget(transform.position, enemy.transform.position, charInfo.supportAtkPosOffset), fDuration).setEase(charInfo.moveForwardTween);
				else
					LeanTween.move(gameObject, BattleUtil.GetTargetAttackPos(transform.position, enemy.transform.position, charInfo.myRadius + enemy.charInfo.myRadius), fDuration).setEase(charInfo.moveForwardTween);
			}
			else {//dir=="b"
				LeanTween.move(gameObject, originalPos, fDuration).setEase(charInfo.moveBackTween);
			}
		}
	}

	//원호 공격 발동
	public void supportatk(System.Object[] objs)
	{
		Debug.Log("supportatk");
	}
	
	//원호 방어 발동
	public void supportdef(System.Object[] objs)
	{
		Debug.Log("supportdef");
	}
	
	//원호 방어 가드 액션시//
	public void guard(System.Object[] objs)
	{
		Debug.Log("guard");
	}


	//투사체 발사 시점
	public void cast(System.Object[] objs)
	{
		if(charInfo.isCaster )
		{
			GameObject go = Instantiate( BattleResManager.Instance.projectileResDic[charModel.ToString()].projectile) as GameObject;
			go.transform.parent = castPointTrans;
			BattleUtil.ClearTransformLocal(go.transform);
			go.transform.parent = null;
			go.SetActive(true);
			go.transform.rotation = Quaternion.identity;
			projectile = go.AddComponent<CharViewerProjectile>();
			projectile.hitFXPrefab = BattleResManager.Instance.projectileResDic[charModel.ToString()].hit;
			projectile.info = charInfo.projectileInfo;
			Vector3 targetPos = Vector3.zero;
			if(enemy.damagePointTrans == null) {
				targetPos = enemy.transform.position;
				targetPos.y+= 1;
			}
			else {
				targetPos = enemy.damagePointTrans.TransformPoint(enemy.damagePointTrans.localPosition);

			}
			if(targetPos != Vector3.zero)
				go.transform.LookAt(targetPos);
			projectile.MoveToTarget(this, enemy ,targetPos);
		}
	}

	public void cameraidle(System.Object[] objs)
	{
		Debug.Log("camera idle");
		if(!CharacterViewer.Instance.turnOffSkillCam)
			CharacterViewer.Instance.BackToOriginalCamPos(1);
	}
	
	public void cameraidleinstant(System.Object[] objs)
	{
		Debug.Log("camera idle instant");
		if(!CharacterViewer.Instance.turnOffSkillCam)
			CharacterViewer.Instance.BackToOriginalCamPos(1);
	}
	
	public void lighttransform_modify(System.Object[] objs)
	{
		Debug.Log("lighttransform_modify");
		//BattleManager.Instance.realTimeLightLocalRotation = EventlineStaticActor.RealTimeLight.transform.localRotation;
	}
	
	public void lighttransform_original(System.Object[] objs)
	{
		Debug.Log("lighttransform_original");
		//EventlineStaticActor.RealTimeLight.transform.localRotation = BattleManager.Instance.realTimeLightLocalRotation;
	}
	
	//카메라 쉐이크 이후 middle카메라 원점으로 돌리기//
	protected void camerashakeclear()
	{
		CharacterViewer.Instance.middleCam.transform.localPosition = Vector3.zero;
		CharacterViewer.Instance.middleCam.transform.localRotation = Quaternion.identity;
		CharacterViewer.Instance.middleCam.transform.localScale = Vector3.one;
	}
}
